//
//  DDUploadFile.m
//  MyClouds
//
//  Created by sarah doo on 13-8-11.
//  Copyright (c) 2013年 sarah doo. All rights reserved.
//

#import "DDUploadFile.h"
#import "NSMutableData+Replace.h"
@implementation DDUploadFile


- (id)initWithData:(NSData *)data {
    self = [super initWithData:data];
    return self;
}

- (id)initWithFileInfo:(DDFileInfo *)fileInfo{
    self = [super init];
    int uid = [fileInfo fileId];
    /*--------------------放入文件ID-------------*/
    NSData* uidData = [[NSData alloc]initWithBytes:&uid length:sizeof(uid)];
    NSRange range;
    range.location = HEADER_LENGTH;
    range.length = 4;
    [entity replaceBytesInRange:range withBytes:[uidData bytes]];
    /*--------------------放入文件名称------------*/
    NSString* fileName = [fileInfo fileName];
    range.location = range.location + range.length;
    range.length = MAX_PATH * 2;
    [entity replaceByString:fileName length:(MAX_PATH * 2) offset:range.location];
    
    /*--------------------放入文件长度------------*/
    long length = [fileInfo fileLength];
    NSData* lengthData = [[NSData alloc]initWithBytes:&length length:LONG_SIZE];
    range.location = range.location + range.length;
    range.length = LONG_SIZE;
    [entity replaceBytesInRange:range withBytes:[lengthData bytes]];
    
    /*-------------------放入命令和长度，计算CRC----*/
    [self setCmd:CloudCmd_UploadFile];
    [self setLength:[entity length]];
    int crc = [self crcs:entity withLength:[entity length]];
    [self setCrc:crc];
    
    return self;
}

- (DDFileInfo*)getFileInfo{
    DDFileInfo* fileInfo = [[DDFileInfo alloc]init];
    NSRange range;
    range.location = HEADER_LENGTH;
    range.length = INT_SIZE;
    NSData* uidData = [entity subdataWithRange:range];
    int uid = [self dataToInt:uidData];
    [fileInfo setFileId:uid];
    
    range.location = range.location + range.length;
    range.length = MAX_PATH * 2;
    NSData* nameData = [entity subdataWithRange:range];
    NSString* fileName = [self dataToString:nameData];
    [fileInfo setFileName:fileName];
    
    range.location = range.location + range.length;
    range.length = LONG_SIZE;
    long len = 0;
    NSData* lengthData = [entity subdataWithRange:range];
    [lengthData getBytes:&len length:LONG_SIZE];
    //long length = [self dataToLong:lengthData];
    [fileInfo setFileLength:len];
    
    return fileInfo;
}

@end
